<?php

namespace App\Http\Controllers;

use App\Http\Models\User;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\View;
use App\Http\Models\Code;
use App\Http\Models\WebChat;


class HomeController extends Controller
{

    public function getIndex()
    {
        if (!User::loginAttempt(array('CWebChatID' => Session::get('CWebChatID')))) {
            return Redirect::to('register');
        }
        return view('home/index');
    }

    public function getLogin()
    {
        return view('member/index', array('title' => '会员登陆'));
    }

    public function getRegister()
    {

        $title = '会员注册';
        $menu_hide = true;

        if (!Session::get('CWebChatID')) {
            $webUser = WebChat::getUser();
            if (!isset($webUser->openid)) {
                die('Access Denied!');
            }
            $input['CWebChatID'] = $webUser->openid;

            if (User::loginAttempt($input)) {
                return Redirect::to('member/index');
            }
        }

        return view('member/register', compact('title', 'menu_hide'));

    }

    //会员注册
    public function postRegister()
    {
        $title = '会员注册';

        $user = new User();

        $validate = Validator::make(Input::all(), User::$rule);

        if (!Code::Check(Input::all())) {
            $error = $validate->errors()->add('code', '手机验证码错误');

            return view('member/register', compact('title', 'error'))->with('input', Input::all());
        }


        if ($validate->fails()) {

            $error = $validate->messages();

            return View::make('member/register', compact('title', 'error', 'menu_hide'))->with('input', Input::all());
        }

        $user->doSave(Input::all());
        //删除验证码
        Code::where(array('ctype' => '1', 'CMobile' => Input::get('CMobile')))->delete();

        $success = '注册成功!';

        $entry = User::Auth();

        return view('member/index', compact('title', 'success', 'entry'));
    }

    public function getBinding()
    {
        $title = '会员绑定';
        $menu_hide = true;

        if (!Session::get('CWebChatID')) {
            $webUser = WebChat::getUser();
            if (!isset($webUser->openid)) {
                die('Access Denied!');
            }
            $input['CWebChatID'] = $webUser->openid;

            if (User::loginAttempt($input)) {
                return Redirect::to('member/index');
            }
        }

        return view('member/binding', compact('title', 'menu_hide'));
    }

    public function postBinding()
    {
        $model = new User();
        if ($user = $model->bindingCheck(Input::get('CMobile', 0), Input::get('CPwd', 0))) {
            $model->binding($user);
            return Redirect::to('/');
        } else {
            return Redirect::back()->withError('账号或密码错误');
        }
    }

    public function getCode()
    {

        return Code::sendSMS(Input::all());
    }

    //微信绑定验证
    public function getMessage()
    {
        define("TOKEN", "zhiyee");
        $wechatObj = new WebChat();
        $wechatObj->valid();
//        if (!isset($_GET['echostr'])) {
//            $this->responseMsg();
//        } else {
//            $this->checkSignature();
//        }
    }

    public function getAbout()
    {
        $title = '地丰体育简介';
        return view('home.about', compact('title'));
    }

    public function responseMsg()
    {

        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

        if (!empty($postStr)) {
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $fromUsername = $postObj->FromUserName;
            $toUsername = $postObj->ToUserName;
            $keyword = trim($postObj->Content);
            $MsgEvent = $postObj->Event;
            if ($MsgEvent == 'CLICK') {
                $keyword = $postObj->EventKey;
            }
            //$keyword = trim($postObj->key);
            $time = time();
//            $model = D('test');
//            $data['content'] = $keyword;
//            $data['openid'] = $fromUsername . '';
//            //$data['text_content'] = serialize($postObj->toArray());
//            $model->doSave($data);
            DB::insert('insert into tests (content,openid) values (?)', [$keyword, $fromUsername]);
            $textTpl = "<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[%s]]></MsgType>
                        <Content><![CDATA[%s]]></Content>
                        <FuncFlag>0</FuncFlag>
                        </xml>";
            if ($keyword == "?" || $keyword == "？") {
                $msgType = "text";
                $contentStr = date("Y-m-d H:i:s", time()) . '<img src="http://www.php361.cn/Public/image/logo.png" alt=""/>';
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                echo $resultStr;
            } else if ($keyword == 1) {
                $msgType = "text";
                $contentStr = "openid:" . $fromUsername;
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                echo $resultStr;
            } else if ($keyword == 2) {
                $textTpl = "<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[news]]></MsgType>
                            <ArticleCount>1</ArticleCount>
                            <Articles>
                            <item>
                            <Title><![CDATA[%s]]></Title>
                            <Description><![CDATA[%s]]></Description>
                            <PicUrl><![CDATA[%s]]></PicUrl>
                            <Url><![CDATA[%s]]></Url>
                            </item>

                            </Articles>
                            </xml>";
                //$msgType = "text";
                $contentStr = "openid:" . $fromUsername;
                $title = '标题测试';
                $description1 = '描述测试';
                $picurl = 'http://www.php361.cn/Public/image/logo.png';
                $url = 'www.php361.cn';
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $title, $description1, $picurl, $url);
                echo $resultStr;
            } else {
                $msgType = "text";
                $contentStr = date("Y-m-d H:i:s", time()) . '<img src="http://www.php361.cn/Public/image/logo.png" alt=""/>';
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                echo $resultStr;
            }
        } else {
            echo "";
            exit;
        }
    }

    private function checkSignature()
    {
        // you must define TOKEN by yourself
        if (!defined("TOKEN")) {
            throw new Exception('TOKEN is not defined!');
        }

        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }

    public function getClean()
    {
        Session::flush();
        header("Content-Type: text/html;charset=utf-8");
        exit('清理登陆痕迹成功，请重新从菜单进入！');
    }
}
